import json, secrets, string
import base64, requests
# import DataAccess as DA
import requests


api_user = '4168c855dff37db6'
passcode = 'bRq2cHSkieLb4E4K09CGXOC0Oxjx9BMuKfLy5NHtAdjkO'


def generate_password(length=12):
    # alphabet = string.ascii_letters + string.digits + string.punctuation
    alphabet = string.ascii_letters + string.digits
    password = ''.join(secrets.choice(alphabet) for _ in range(length))
    return password

def emqxAPI(apiName, method, payload=''):
    try:
        base = 'http://106.14.208.205:18083/api/v5'
        url = base + apiName
        headers = {
        'Content-Type' : 'application/json',
        'Authorization': "Basic " + base64.b64encode((api_user + ":" + passcode).encode()).decode()
        }
        response = requests.request(method, url, headers=headers, data=json.dumps(payload))
        if response.status_code == 200 or response.status_code == 201: 
            return True, response.text
        else:
            print('API错误: %s' % response.text)
            return False, response.text
    except Exception as e:
        print('API error: %s' % str(e))
        return False, ''


def getUserList():
    success, res = emqxAPI('/authentication/password_based%3Abuilt_in_database/users', 'GET')
    if success:
        res = json.loads(res)
        userList = res['data']
        for user in userList:
            print(user)
        return True        
    else:
        print('获取用户清单失败 %s' % json.loads(res)['message'] )    # print(userList)
        return False
    
    return False, []

def newUser(id, password):    
    DA.ConnectMongo()
    
    payload={
        "user_id": id,
        "password": password,  
    }
    success, res = emqxAPI('/authentication/password_based%3Abuilt_in_database/users', 'POST', payload=payload)
    if success:        
        print('新用户创建成功')
        return True,         
    else:
        print('创建新用户失败 %s' % json.loads(res)['message'] )    # print(userList)
        return False, ''

def newDevice(product, SN):
    newUser(product + '-' + SN, generate_password())
    

# newUser('Floc789', generate_password())
newDevice('FlocPi', '665')
getUserList()